<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商品编号" prop="supplierCommodityNo">
        <el-input v-model="queryParams.supplierCommodityNo" placeholder="请输入商品编号" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="商品名称" prop="supplierCommodityName">
        <el-input v-model="queryParams.supplierCommodityName" placeholder="请输入商品名称" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item label="商品类别" prop="supplierCommodityType">
        <el-cascader ref="commodityType" :options="options" v-model="supplierCommodityType" :props="props"
          clearable></el-cascader>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['erp:ErpSupplierCommodity:add']">新增供应商商品</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-upload2" size="mini" @click="handleImport"
          v-hasPermi="['erp:ErpSupplierCommodity:import']">批量导入</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-row :gutter="20">
      <!--商品类型数据-->
      <el-col :span="3" :xs="24">
        <div class="head-container">
          <el-tree :data="commodityTypeOptions" :props="defaultProps" :expand-on-click-node="false" ref="tree"
            node-key="id" default-expand-all highlight-current @node-click="handleNodeClick" />
        </div>
      </el-col>
      <!--商品数据-->
      <el-col :span="21" :xs="24">
        <el-table v-loading="loading" :data="ErpSupplierCommodityList" @selection-change="handleSelectionChange" border>
          <el-table-column label="商品编号" align="center" prop="supplierCommodityNo" />
          <el-table-column label="商品名称" align="center" prop="supplierCommodityName" />
          <el-table-column label="商品图片" align="center" prop="supplierCommodityImg" width="100px;">
            <template slot-scope="scope">
              <image-preview :src="scope.row.supplierCommodityImg" :width="50" :height="50" />
            </template>
          </el-table-column>
          <el-table-column label="商品类别" align="center" prop="commodityTypeName" />
          <el-table-column label="规格" align="center" prop="supplierCommoditySpec" />
          <el-table-column label="单位" align="center" prop="supplierCommodityUnit" width="100px;"/>
          <el-table-column label="商品报价" width="120" align="center" prop="supplierCommodityQuotation">
            <template slot-scope="scope">
              <span>{{ formattedNumber(scope.row.supplierCommodityQuotation) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                v-hasPermi="['erp:ErpSupplierCommodity:edit']">修改</el-button>
              <!-- <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                v-hasPermi="['erp:ErpSupplierCommodity:remove']">删除</el-button> -->
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize" @pagination="getList" />
      </el-col>
    </el-row>

    <!-- 添加或修改供应商商品对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="商品名称" prop="supplierCommodityName">
              <el-input v-model="form.supplierCommodityName" placeholder="请输入商品名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品编号" prop="supplierCommodityNo">
              <el-input v-model="form.supplierCommodityNo" placeholder="请输入商品编号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="商品类别" prop="supplierCommodityTypes">
              <el-cascader ref="cascader" :options="options" v-model="form.supplierCommodityTypes" :props="{
                expandTrigger: 'hover',
                value: 'commodityTypeId',
                label: 'commodityTypeName',
                checkStrictly: true,
              }" clearable @change="handleTypeChange"></el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品规格" prop="supplierCommoditySpec">
              <el-input v-model="form.supplierCommoditySpec" placeholder="请输入商品规格" />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="类型编码" prop="supplierTypeCode">
              <el-input v-model="form.supplierTypeCode" :disabled="isDisabled" placeholder="商品类型编码组合" />
            </el-form-item>
          </el-col> -->
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="商品单位" prop="supplierCommodityUnit">
              <el-input v-model="form.supplierCommodityUnit" placeholder="请输入商品单位" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品报价" prop="supplierCommodityQuotation">
              <el-input type="number" v-model="form.supplierCommodityQuotation" placeholder="请输入商品报价" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="商品描述" prop="supplierCommodityDescribe">
              <el-input v-model="form.supplierCommodityDescribe" placeholder="请输入商品描述" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="商品图片" prop="supplierCommodityImg">
              <image-upload v-model="form.supplierCommodityImg" @input="handleImageInput" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="商品详情">
              <editor v-model="form.supplierCommodityImgtext" :min-height="192" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer-options">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 商品导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport + '&supplierId=' + queryParams.supplierId" :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <!-- <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的商品数据
          </div> -->
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
            @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listErpSupplierCommodity, getErpSupplierCommodity, delErpSupplierCommodity, addErpSupplierCommodity, updateErpSupplierCommodity } from "@/api/erp/ErpSupplierCommodity";
import { listErpCommodityType } from "@/api/erp/ErpCommodityType";
import { getToken } from "@/utils/auth";
import asc from '@/utils/asc'
import {formattedNumber} from "@/utils/ruoyi";

export default {
  name: "ErpSupplierCommodity",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 商品类别
      options: [],
      // 总条数
      total: 0,
      // 供应商商品表格数据
      ErpSupplierCommodityList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 30,
        supplierCommodityName: null,
        supplierCommodityNo: null,
        supplierCommodityType: null,
        supplierId: null
      },
      supplierCommodityType: [],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        supplierCommodityName: [
          { required: true, message: "商品名称不能为空", trigger: "blur" }
        ],
        supplierCommodityNo: [
          { required: true, message: "商品编号不能为空", trigger: "blur" }
        ],
        supplierCommodityTypes: [
          { required: true, message: "商品类别不能为空", trigger: "blur" }
        ],
        // supplierTypeCode: [
        //   { required: true, message: "类别编码不能为空", trigger: "blur" }
        // ],
        supplierCommodityUnit: [
          { required: true, message: "商品单位不能为空", trigger: "blur" }
        ],
        supplierCommodityQuotation: [
          { required: true, message: "商品报价不能为空", trigger: "blur" }
        ],
      },
      // 商品类别配置选项
      props: {
        multiple: true,
        checkStrictly: true,
        value: 'commodityTypeId',
        label: 'commodityTypeName',
      },
      // 左侧商品类别树
      commodityTypeOptions: [],
      defaultProps: {
        children: "children",
        label: "commodityTypeName"
      },
      // 禁用商品类别编码组合字段
      isDisabled: true,
      // 商品导入参数
      upload: {
        // 是否显示弹出层（商品导入）
        open: false,
        // 弹出层标题（商品导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的商品数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/erp/ErpSupplierCommodity/importData"
      },
    };
  },
  created() {
    const supplierId = this.$route.params && this.$route.params.supplierId;
    if (supplierId) {
      this.queryParams.supplierId = supplierId;
      this.getList();
    }
    this.getListCommodityType();
  },
  methods: {
    formattedNumber,
    /** 查询供应商商品列表 */
    getList() {
      this.loading = true;
      listErpSupplierCommodity(this.queryParams).then(response => {
        this.ErpSupplierCommodityList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 获取商品类别 */
    getListCommodityType() {
      listErpCommodityType().then(response => {
        this.options = this.handleTree(response.data, "commodityTypeId", "commodityTypePid");
        this.commodityTypeOptions = [];
        const data = { commodityTypeId: 0, commodityTypeName: '全部', children: [] };
        data.children = this.handleTree(response.data, "commodityTypeId", "commodityTypePid");
        this.commodityTypeOptions.push(data);
      })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        supplierCommodityId: null,
        supplierId: this.queryParams.supplierId,
        supplierCommodityName: null,
        supplierCommodityNo: null,
        supplierCommodityType: null,
        // supplierTypeCode: null,
        supplierCommoditySpec: null,
        supplierCommodityBrand: null,
        supplierCommodityUnit: null,
        supplierCommodityQuotation: null,
        supplierCommodityImg: null,
        supplierCommodityImgtext: null,
        supplierCommodityDescribe: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      let nodes = this.$refs.commodityType.getCheckedNodes();
      if (nodes.length > 0 && this.supplierCommodityType.length > 0) {
        let nodeIds = nodes.map((item) => item.value);
        this.queryParams.supplierCommodityType = nodeIds.join("|");
      }
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.supplierCommodityType = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.supplierCommodityId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加供应商商品";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const supplierCommodityId = row.supplierCommodityId || this.ids
      getErpSupplierCommodity(supplierCommodityId).then(response => {
        this.form = response.data;
        this.form.supplierCommodityTypes = this.form.supplierCommodityType?.split(',').map(Number);
        this.open = true;
        this.title = "修改供应商商品";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.supplierCommodityType = this.form.supplierCommodityTypes?.join(',');
          if (this.form.supplierCommodityImgtext) {
            this.form.supplierCommodityImgtext = asc.encrypt(
              this.form.supplierCommodityImgtext
            );
          }
          if (this.form.supplierCommodityId != null) {
            updateErpSupplierCommodity(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addErpSupplierCommodity(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const supplierCommodityIds = row.supplierCommodityId || this.ids;
      this.$modal.confirm('是否确认删除供应商商品编号为"' + supplierCommodityIds + '"的数据项？').then(function () {
        return delErpSupplierCommodity(supplierCommodityIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.supplierCommodityType =
        data.commodityTypeId == 0 ? null : data.commodityTypeId;
      this.handleQuery();
    },
    // 图片上传成功
    handleImageInput(e) {
      this.form.supplierCommodityImg = e;
    },
    // 商品类别选择
    handleTypeChange(e) {
      // let nodesObj = this.$refs['cascader'].getCheckedNodes();
      // if (nodesObj.length > 0) {
      //   let code = [];
      //   nodesObj[0].pathNodes.forEach(i => {
      //     code.push(i.data.commodityTypeNo);
      //   })
      //   this.isDisabled = false;
      //   this.form.supplierTypeCode = code?.join(',');
      //   this.isDisabled = true;
      // }
    },
     /** 导入按钮操作 */
     handleImport() {
      this.upload.title = "商品导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('erp/ErpSupplierCommodity/importTemplate', {
      }, `商品导入_template_${new Date().getTime()}.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
  }
};
</script>
<style lang="css" scoped>
  .el-cascader--medium {
    width: 100%;
  }

  ::v-deep .el-table__cell{
    padding: 0px;
  }

  ::v-deep .el-table .cell .el-image{
    width: 30px !important;
    height: 30px !important;
    margin-top:5px;
  }
</style>
